<?php
/**
 * ResMania
 * More Information contact: info@resmania.com
 *
 * @package Joomla Connector
 * @version 0.5
 * @author webformatique
 * @copyright (C) 2010- webformatique
 * @license GNU/GPLv3 http://www.gnu.org/copyleft/gpl.html
 */

// no direct access
defined('_JEXEC') or die('Restricted access');


if (RM_Joomla_Connector::is15()){
    // joomla specific files needed for include because will not be included by Zend.
    include_once(JPATH_ROOT.DS.'libraries'.DIRECTORY_SEPARATOR.'joomla'.DIRECTORY_SEPARATOR.'mail'.DIRECTORY_SEPARATOR.'helper.php');
    include_once(JPATH_ROOT.DS.'libraries'.DIRECTORY_SEPARATOR.'joomla'.DIRECTORY_SEPARATOR.'user'.DIRECTORY_SEPARATOR.'helper.php');
    include_once(JPATH_ROOT.DS.'libraries'.DIRECTORY_SEPARATOR.'joomla'.DIRECTORY_SEPARATOR.'user'.DIRECTORY_SEPARATOR.'user.php');
    include_once(JPATH_ROOT.DS.'libraries'.DIRECTORY_SEPARATOR.'joomla'.DIRECTORY_SEPARATOR.'user'.DIRECTORY_SEPARATOR.'authorization.php');
    include_once(JPATH_ROOT.DS.'libraries'.DIRECTORY_SEPARATOR.'joomla'.DIRECTORY_SEPARATOR.'database'.DIRECTORY_SEPARATOR.'table'.DIRECTORY_SEPARATOR.'user.php');
    include_once(JPATH_ROOT.DS.'libraries'.DIRECTORY_SEPARATOR.'joomla'.DIRECTORY_SEPARATOR.'database'.DIRECTORY_SEPARATOR.'recordset.php');
    include_once(JPATH_ROOT.DS.'libraries'.DIRECTORY_SEPARATOR.'joomla'.DIRECTORY_SEPARATOR.'utilities'.DIRECTORY_SEPARATOR.'arrayhelper.php');
}

if (RM_Joomla_Connector::is16()){
    include_once(JPATH_ROOT.DS.'libraries'.DIRECTORY_SEPARATOR.'joomla'.DIRECTORY_SEPARATOR.'application'.DIRECTORY_SEPARATOR.'component'.DIRECTORY_SEPARATOR.'model.php');
    include_once(JPATH_ROOT.DS.'libraries'.DIRECTORY_SEPARATOR.'joomla'.DIRECTORY_SEPARATOR.'mail'.DIRECTORY_SEPARATOR.'helper.php');
    include_once(JPATH_ROOT.DS.'libraries'.DIRECTORY_SEPARATOR.'joomla'.DIRECTORY_SEPARATOR.'user'.DIRECTORY_SEPARATOR.'helper.php');
    include_once(JPATH_ROOT.DS.'libraries'.DIRECTORY_SEPARATOR.'joomla'.DIRECTORY_SEPARATOR.'user'.DIRECTORY_SEPARATOR.'user.php');
    include_once(JPATH_ROOT.DS.'libraries'.DIRECTORY_SEPARATOR.'joomla'.DIRECTORY_SEPARATOR.'user'.DIRECTORY_SEPARATOR.'authentication.php');
    include_once(JPATH_ROOT.DS.'libraries'.DIRECTORY_SEPARATOR.'joomla'.DIRECTORY_SEPARATOR.'database'.DIRECTORY_SEPARATOR.'table'.DIRECTORY_SEPARATOR.'user.php');
    include_once(JPATH_ROOT.DS.'libraries'.DIRECTORY_SEPARATOR.'joomla'.DIRECTORY_SEPARATOR.'utilities'.DIRECTORY_SEPARATOR.'arrayhelper.php');
}

class RM_Joomla_Model_Users extends RM_Users {
    private $_userColumnName = 'cms_id';

    public function createRow(array $data = array(), $defaultSource = null){
        $cmsUser = RM_Environment::getConnector()->getUser();
        if ($cmsUser->isGuest() == false) {
            $data[$this->_userColumnName] = $cmsUser->getUser()->get('id');
            if ($data['email'] != $cmsUser->getUser()->get('email')) {
                $result = $this->_save($data, false, true);
            }
        } else {
            $result = $this->_save($data, false, true);
        }

        $pResult = parent::createRow($data, $defaultSource);
        return $pResult;
    }

    public function insert($userDetails){
        $cmsUser = RM_Environment::getConnector()->getUser();

        //We need to check if this is Admin end, we don't need to use cmsUser id
        if (RM_Environment::getConnector()->getModule() != 'admin'){
            if ($cmsUser->isGuest() == false) {
                $userDetails[$this->_userColumnName] = $cmsUser->getUser()->get('id');
                return parent::insert($userDetails);
            }
        }

        try {
            $joomlaUserID = $this->_save($userDetails);
        } catch (RM_Exception $e) {
            RM_Log::toLog($e->getMessage());
            //throw $e;
        }

        $userDetails[$this->_userColumnName] = $joomlaUserID;
        // parent special key command will resolve the insert function in the parent classes.
        // (IE: if not resolved in RM_Users, will go to parent class of RM_Users for resolution)
        return parent::insert($userDetails);
    }

    public function update($userDetails){
        $userID = $userDetails['id'];
        $joomlaUser = $this->_save($userDetails, true);
        $userDetails[$this->_userColumnName] = $joomlaUser;
        $userDetails['id'] = $userID;
        return parent::update($userDetails, "id='".$userDetails['id']."'");
    }

    public function delete(array $ids){
        $errors = array();
        foreach ($ids as $userID) {
            $coreModel = new RM_Users();
            $coreUser = $coreModel->find($userID)->current();
            if ($coreUser == null) continue;
            $joomlaID = $coreUser->cms_id;
            $coreUser->delete();
            if ($joomlaID == '') continue;

            $joomlaUser = clone(JFactory::getUser());
            $joomlaUser->id = $joomlaID;
            $joomlaUser->delete();
            $errors = array_merge($errors, $joomlaUser->getErrors());
        }
        return $errors;
    }

    private function _checkConfig(){
        // If user registration is allowed then return true.
        $usersConfig = &JComponentHelper::getParams( 'com_users' );
        if ($usersConfig->get('allowUserRegistration') == '1') {
            return true;
        }
        return false;
    }

    /**
     * Generates username using userdetails
     *
     * @param array $userDetails
     * @return string
     */
    private function _generateUsername($userDetails){
        return $userDetails['first_name'].'_'.time();
    }

    private function _save($userDetails, $updateOnly = false, $checkOnly = false)
    {
        /*
        //TODO: we need to think in what situation we need to checking this option from Joomla,
        //cause if we are here we already have a Resmania option to create CMS users on already.         
        if (!$this->_checkConfig()) {
            return false;
        }
         */
        if ($updateOnly) {
            $userID = JUserHelper::getUserId($userDetails['username']); // get the joomla id
            $user = JFactory::getUser($userID);
            $userDetails['id'] = $userID;
        } else {
            $user = JFactory::getUser(0);
        }

        $newUsertype = "Registered";
        $userDetails['usertype'] = $newUsertype;

        if (RM_Joomla_Connector::is15()){
            $authorize =& JFactory::getACL();
            $userDetails['gid'] = $authorize->get_group_id( '', $newUsertype, 'ARO' );
        }

        $userDetails['activation'] = 1;
        $userDetails['block'] = 0;
        if (isset($userDetails['password'])) {
            $userDetails['password2'] = $userDetails['password'];
        }
        $userDetails['name'] = $userDetails['first_name']." ".$userDetails['last_name'];
        if ($userDetails['username'] == null) {
            $userDetails['username'] = $this->_generateUsername($userDetails);
        }

        if (!$updateOnly){
            // these are set on a new user
            $userDetails['id']= 0;
            $userDetails['registerDate'] = date('Y-m-d');
        } else {
            // these are set for an update to an account.
            $userDetails['RM_id'] = $userDetails['id']; // save the ResMania ID for use later as Joomla requires this as 'id'
        }

        if (!$user->bind( $userDetails )) {
            throw new RM_Exception($user->getError());
        }

        if ($checkOnly) {
            $table =& $user->getTable();
            if (RM_Joomla_Connector::is15()){
                $user->params = $user->_params->toString();
            }
            $table->bind($user->getProperties());

            if (!$table->check()) {
                throw new RM_Exception($table->getError()); //we just need the first one
            } else {
                return true;
            }
        }

        $result = $user->save($updateOnly);
        if ( !$result ) {
            //Here could be errors:
            //1.'Please enter your name.' (translated) - this error should be handled by our own validator
            //2.'Please enter a user name.' (translated) - this error should be handled by our own validator
            //3.VALID_AZ09 : wrong chars in username - this error should be handled by our own validator
            //4.WARNREG_MAIL : email address is wrong (have wrong format) - this error should be handled by our own validator
            //5.WARNREG_INUSE : username is already registered
            //6.WARNREG_EMAIL_INUSE : email address is already in database
            //7.WARNSUPERADMINCREATE : non super admin tries to create a superadmin - this error is useless as long as we will not create joomla superadmin
            //8.WARNSUPERADMINCREATE : non super admin tries to creata an admin - this error is useless as long as we will not create joomla admin
            $errors = $user->getErrors();
            throw new RM_Exception($errors[0]); //we just need the first one
        }

        // if this a new user then return the joomla user id, if it's an update then don't return anythib
        $id = JUserHelper::getUserId($userDetails['username']);

        if (RM_Joomla_Connector::is16()){
            $db = $user->getTable()->getDbo();
            //This is a 'Registered' group.
            $db->setQuery('INSERT INTO `#__user_usergroup_map` (`user_id`, `group_id`) VALUES ('.$id.', 2)');
			$db->query();
        }

        return $id;
    }
}